/*
 * Copyright (C) 1994-2021 Altair Engineering, Inc.
 * For more information, contact Altair at www.altair.com.
 *
 * This file is part of both the OpenPBS software ("OpenPBS")
 * and the PBS Professional ("PBS Pro") software.
 *
 * Open Source License Information:
 *
 * OpenPBS is free software. You can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * OpenPBS is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Commercial License Information:
 *
 * PBS Pro is commercially licensed software that shares a common core with
 * the OpenPBS software.  For a copy of the commercial license terms and
 * conditions, go to: (http://www.pbspro.com/agreement.html) or contact the
 * Altair Legal Department.
 *
 * Altair's dual-license business model allows companies, individuals, and
 * organizations to create proprietary derivative works of OpenPBS and
 * distribute them - whether embedded or bundled with other software -
 * under a commercial license agreement.
 *
 * Use of Altair's trademarks, including but not limited to "PBS™",
 * "OpenPBS®", "PBS Professional®", and "PBS Pro™" and Altair's logos is
 * subject to Altair's trademark licensing policies.
 */

/**
 * @brief
 * geteusernam.c	- Functions relating to effective user name
 *
 *	Included public functions are:
 *
 *	determine_euser
 *	determine_egroup
 *	set_objexid
 */
#include <pbs_config.h> /* the master config generated by configure */

#include <sys/types.h>
#include <sys/param.h>
#include <grp.h>
#include <pwd.h>
#include "pbs_ifl.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "server_limits.h"
#include "list_link.h"
#include "attribute.h"
#include "job.h"
#include "reservation.h"
#include "server.h"
#include "pbs_error.h"
#include "pbs_nodes.h"
#include "svrfunc.h"

/* External Data */

/**
 * @brief
 *  	determine_euser - determine the effective user name
 *
 *  	Determine with which "user name" this object is to be associated
 *  	 1. from user_list use name with host name that matches this host
 *  	 2. from user_list use name with no host specification
 *  	 3. user owner name
 *
 * @see
 *		set_objexid
 *
 * @param[in]	objtype - object type
 * @param[in]	pobj -  ptr to object to link in
 * @param[in]	pattr - pointer to User_List attribute
 * @param[in,out]	isowner - Return: 1  if object's owner chosen as euser
 *
 * @return pointer to the user name
 *
 */

static char *
determine_euser(void *pobj, int objtype, attribute *pattr, int *isowner)
{
	char *hit = 0;
	int i;
	struct array_strings *parst;
	char *pn;
	char *ptr;
	attribute *objattr;
	static char username[PBS_MAXUSER + 1];

	memset(username, '\0', sizeof(username));

	/* set index and pointers based on object type */
	if (objtype == JOB_OBJECT)
		objattr = get_jattr((job *) pobj, JOB_ATR_job_owner);
	else
		objattr = get_rattr((resc_resv *) pobj, RESV_ATR_resv_owner);

	/* search the User_List attribute */

	if (is_attr_set(pattr) &&
	    (parst = pattr->at_val.at_arst)) {
		*isowner = 0;
		for (i = 0; i < parst->as_usedptr; i++) {
			pn = parst->as_string[i];
			ptr = strchr(pn, '@');
			if (ptr) { /* if has host specification, check for the complete host name, if host name is incorrect, hit is not set */
				if (!strcasecmp(server_host, ptr + 1)) {
					hit = pn; /* option 1. */
					break;
				}
			} else {	  /* wildcard host (null) */
				hit = pn; /* option 2. */
			}
		}
	}
	if (!is_attr_set(pattr)) { /* if no user is specified, default to the object owner ( 3.) */
		hit = get_attr_str(objattr);
		*isowner = 1;
	}

	/* copy user name into return buffer and strip off host name only when hit is set
	 * i.e. when either no user is specified(in this case, default the job to the object owner)
	 * or a user is provided with the correct host name.
	 * If not set, job can't be run as no user to run the job */
	if (hit) {
		cvrt_fqn_to_name(hit, username);
	}

	return (username);
}

/**
 * @brief
 * 		determine_egroup - determine the effective group name
 *
 * 		Determine (for this host) with which "group name" this object is to be
 * 		associated
 *
 * @par	Functionality:
 *  	1. from group_list use name with host name that matches this host
 *  	2. from group_list use name with no host specification
 *  	3. NULL, not specified
 *
 *	@see
 *		set_objexid
 *
 * @param[in]	objtype - object type
 * @param[in]	pobj -  ptr to object to link in
 * @param[in]	pattr - pointer to group_list attribute
 *
 * Returns pointer to the group name or a NULL pointer
 */

static char *
determine_egroup(void *pobj, int objtype, attribute *pattr)
{
	char *hit = 0;
	int i;
	struct array_strings *parst;
	char *pn;
	char *ptr;
	static char groupname[PBS_MAXUSER + 1];

	/* search the group-list attribute */

	if ((is_attr_set(pattr)) &&
	    (parst = pattr->at_val.at_arst)) {
		for (i = 0; i < parst->as_usedptr; i++) {
			pn = parst->as_string[i];
			ptr = strchr(pn, '@');
			if (ptr) { /* has host specification */
				if (!strncasecmp(server_host, ptr + 1, strlen(ptr + 1))) {
					hit = pn; /* option 1. */
					break;
				}
			} else {	  /* wildcard host (null) */
				hit = pn; /* option 2. */
			}
		}
	}
	if (!hit) /* nothing sepecified, return null */
		return NULL;

	/* copy group name into return buffer, strip host name */
	cvrt_fqn_to_name(hit, groupname);
	return (groupname);
}

/**
 * @brief
 * 		set_objexid - validate and set the object's effective/execution username
 *		and its effective/execution group name attributes.  For jobs, these
 *		are JOB_ATR_euser and JOB_ATR_egroup attributes of the job structure.
 *		For reservations, they are RESV_ATR_euser and RESV_ATR_egroup of the
 *		resc_resv structure.
 *
 * @par	Functionality:
 *		1.  Determine the effective/execution user_name.
 *		1a. Get the password entry for that username.
 *		1b. Uid of 0 (superuser) is not allowed, might cause root-rot
 *		1c. Determine if the object's owner name is permitted to map
 *	    to the effective/execution username
 *		1d. Set the object's effective/execution user_name to the name
 *	    that got determined in the above steps
 *		2.  Determine the effective/execution group name.
 *		2a. Determine if the effective/execution user_name belongs to
 *	    this effective/execution group
 *		2b. Set JOB_ATR_egroup to the execution group name.
 *		2b. Set the object's effective/execution group_name to the name
 *	    that got determined in the above step
 *
 * @see
 *		modify_job_attr, req_resvSub and svr_chkque
 *
 * @param[in]	objtype - object type
 * @param[in]	pobj -  ptr to object to link in
 * @param[in]	pattr - pointer to attribute structure
 * 						which contains group_List attributes and User_List attributes
 *
 * @returns	 int
 * @retval	 0	- if everything got determined and set appropriately else,
 * @retval	non-zero	- error number if something went awry
 */

int
set_objexid(void *pobj, int objtype, attribute *attrry)
{
	int addflags = 0;
	int isowner;
	attribute *pattr;
	char *puser;
	char *pgrpn;
	char *owner;
	int idx_ul, idx_gl;
	int idx_owner, idx_euser, idx_egroup;
	int idx_acct;
	int bad_euser, bad_egrp;
	attribute *objattrs;
	attribute_def *obj_attr_def;
	attribute *paclRoot; /*future: aclRoot resv != aclRoot job*/
	char **pmem;
	struct group *gpent;
	struct passwd *pwent;
	char gname[PBS_MAXGRPN + 1];

	/* determine index values and pointers based on object type */
	if (objtype == JOB_OBJECT) {
		idx_ul = (int) JOB_ATR_userlst;
		idx_gl = (int) JOB_ATR_grouplst;
		idx_owner = (int) JOB_ATR_job_owner;
		idx_euser = (int) JOB_ATR_euser;
		idx_egroup = (int) JOB_ATR_egroup;
		idx_acct = (int) JOB_ATR_account;
		obj_attr_def = job_attr_def;
		objattrs = ((job *) pobj)->ji_wattr;
		owner = get_jattr_str(pobj, idx_owner);
		paclRoot = get_sattr(SVR_ATR_AclRoot);
		bad_euser = PBSE_BADUSER;
		bad_egrp = PBSE_BADGRP;
	} else {
		idx_ul = (int) RESV_ATR_userlst;
		idx_gl = (int) RESV_ATR_grouplst;
		idx_owner = (int) RESV_ATR_resv_owner;
		idx_euser = (int) RESV_ATR_euser;
		idx_egroup = (int) RESV_ATR_egroup;
		idx_acct = (int) RESV_ATR_account;
		obj_attr_def = resv_attr_def;
		objattrs = ((resc_resv *) pobj)->ri_wattr;
		owner = get_rattr_str(pobj, idx_owner);
		paclRoot = get_sattr(SVR_ATR_AclRoot);
		bad_euser = PBSE_R_UID;
		bad_egrp = PBSE_R_GID;
	}

	/* if passed in "User_List" attribute is set use it - this may
	 * be a newly modified one.
	 * if not set, fall back to the object's User_List, which may
	 * actually be the same as what is passed into this function
	 */

	if ((attrry + idx_ul)->at_flags & ATR_VFLAG_SET)
		pattr = attrry + idx_ul;
	else
		pattr = &objattrs[idx_ul];

	if ((puser = determine_euser(pobj, objtype, pattr, &isowner)) == NULL)
		return (bad_euser);

	pwent = getpwnam(puser);
	if (pwent == NULL) {
		if (!get_sattr_long(SVR_ATR_FlatUID))
			return (bad_euser);
	} else if (pwent->pw_uid == 0) {
		if (!is_attr_set(paclRoot))
			return (bad_euser); /* root not allowed */
		if (acl_check(paclRoot, owner, ACL_User) == 0)
			return (bad_euser); /* root not allowed */
	}

	if (!isowner || !get_sattr_long(SVR_ATR_FlatUID)) {
		if (site_check_user_map(pobj, objtype, puser) == -1)
			return (bad_euser);
	}

	pattr = &objattrs[idx_euser];
	free_attr(obj_attr_def, pattr, idx_euser);
	set_attr_generic(pattr, &obj_attr_def[idx_euser], puser, NULL, INTERNAL);

	if (pwent != NULL) {
		/* if account (qsub -A) is not specified, set to empty string */

		pattr = &objattrs[idx_acct];
		if (!is_attr_set(pattr))
			set_attr_generic(pattr, &obj_attr_def[idx_acct], "\0", NULL, INTERNAL);

		/*
		 * now figure out (for this host) the effective/execute "group name"
		 * for the object.
		 * PBS requires that each group have an entry in the group file,
		 * see the admin guide for the reason why...
		 *
		 * use the passed group_list if set, may be a newly modified one.
		 * if it isn't set, use the object's group_list, which may in fact
		 * be same as what was passed
		 */

		if (is_attr_set(attrry + idx_gl))
			pattr = attrry + idx_gl;
		else
			pattr = &objattrs[idx_gl];
		if ((pgrpn = determine_egroup(pobj, objtype, pattr)) != NULL) {

			/* user specified a group, group must exists and either	   */
			/* must be user's primary group	 or the user must be in it */

			gpent = getgrnam(pgrpn);
			if (gpent == NULL) {
				if (pwent != NULL)	   /* no such group is allowed */
					return (bad_egrp); /* only when no user (flatuid)*/

			} else if (gpent->gr_gid != pwent->pw_gid) { /* not primary */
				pmem = gpent->gr_mem;
				while (*pmem) {
					if (!strcmp(puser, *pmem))
						break;
					++pmem;
				}
				if (*pmem == 0)
					return (bad_egrp); /* user not in group */
			}
			addflags = ATR_VFLAG_SET;

		} else {

			/* Use user login group */
			gpent = getgrgid(pwent->pw_gid);
			if (gpent != NULL) {
				pgrpn = gpent->gr_name; /* use group name */
			} else {
				(void) sprintf(gname, "%d", pwent->pw_gid);
				pgrpn = gname; /* turn gid into string */
			}

			/*
			 * setting the DEFAULT flag is a "kludy" way to keep MOM from
			 * having to do an unneeded look up of the group file.
			 * We needed to have JOB_ATR_egroup set for the server but
			 * MOM only wants it if it is not the login group, so there!
			 */
			addflags = ATR_VFLAG_SET | ATR_VFLAG_DEFLT;
		}
	} else {

		/*
		 * null password entry,
		 * set group to "default" and set default for Mom to use login group
		 */

		pgrpn = "-default-";
		addflags = ATR_VFLAG_SET | ATR_VFLAG_DEFLT;
	}

	pattr = attrry + idx_egroup;
	free_attr(obj_attr_def, pattr, idx_egroup);

	if (addflags != 0) {
		set_attr_generic(pattr, &obj_attr_def[idx_egroup], pgrpn, NULL, INTERNAL);
		pattr->at_flags |= addflags;
	}

	return (0);
}
